package com.woniuxy.charin.controller;


import com.woniuxy.charin.model.entity.ChargingGun;
import com.woniuxy.charin.model.entity.ChargingPile;
import com.woniuxy.charin.model.entity.Station;
import com.woniuxy.charin.model.vo.PageResponse;
import com.woniuxy.charin.model.vo.PileAndGunRequest;
import com.woniuxy.charin.service.ChargingGunService;
import com.woniuxy.charin.service.ChargingPileService;
import com.woniuxy.charin.service.StationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/chargingPile")
@Slf4j
@Api(tags = "充电桩管理")
public class ChargingPileController {
    @Autowired
    private ChargingPileService chargingPileService;
    @Autowired
    private StationService stationService;
    @Autowired
    private ChargingGunService chargingGunService;

    @GetMapping("/getChargingPileByStationId/{stationId}")
    @ApiOperation("根据站点id查询其属下所有充电桩")
    public ResponseEntity<List<PileAndGunRequest>> getPileByStationId(@PathVariable Integer stationId) {
        log.info("Fetching piles and charging guns for stationId={}", stationId);

        // 调用 Service 方法获取站点下所有充电桩
        List<ChargingPile> chargingPiles = chargingPileService.getChargingPileByStationId(stationId);

        if (chargingPiles == null || chargingPiles.isEmpty()) {
            return ResponseEntity.notFound().build();
        }

        // 遍历充电桩列表，组装响应对象
        List<PileAndGunRequest> responseList = chargingPiles.stream().map(chargingPile -> {
            PileAndGunRequest response = new PileAndGunRequest();
            response.setChargingPile(chargingPile);

            // 获取每个充电桩下的充电枪
            List<ChargingGun> chargingGuns = chargingGunService.listByChargingPileId(chargingPile.getId());
            response.setChargingGuns(chargingGuns);

            return response;
        }).collect(Collectors.toList());

        return ResponseEntity.ok(responseList);
    }

    //根据充电桩id查到充电桩和充电枪的信息
    @GetMapping("/getChargingPileWithChargingGun/{id}")
    @ApiOperation("根据充电桩id查到充电桩和充电枪的信息")
    public PileAndGunRequest getChargingPileWithChargingGun(@PathVariable Integer id) {
        log.info("根据充电桩id查到充电桩和充电枪的信息");
        ChargingPile chargingPile = chargingPileService.getChargingPileById(id);
        if (chargingPile == null) {
            throw new RuntimeException("Charging pile not found with id: " + id);
        }
        Long PileId = Long.valueOf(id);
        List<ChargingGun> chargingGuns = chargingGunService.listByChargingPileId(PileId);
        PileAndGunRequest response = new PileAndGunRequest();
        response.setChargingPile(chargingPile);
        response.setChargingGuns(chargingGuns);
        return response;
    }

    //分页查询
    @GetMapping("/getChargingPileByPage")
    @ApiOperation("分页查询充电桩信息")
    public PageResponse<ChargingPile> getChargingPileList(
            @RequestParam(required = false) String pileName,
            @RequestParam(required = false) String pileCode,
            @RequestParam(required = false) String pileStatus,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "5") int size) {
        log.info("分页查询充电桩信息");
        return chargingPileService.getChargingPileList(pileName, pileCode, pileStatus, page, size);
    }

    //下线充电桩
    @PutMapping("/offlineChargingPile/{id}")
    @ApiOperation("设置充电桩为空闲中")
    public String offlineChargingPile(@PathVariable int id) {
        log.info("offlineChargingPile");
        chargingPileService.offlineChargingPile(id);
        return "下线成功";
    }

    //上线充电桩
    @PutMapping("/onlineChargingPile/{id}")
    @ApiOperation("设置充电桩为使用中")
    public String onlineChargingPile(@PathVariable int id) {
        log.info("onlineChargingPile");
        chargingPileService.onlineChargingPile(id);
        return "上线成功";
    }

    //故障中
    @PutMapping("/setChargingPileCracked/{id}")
    @ApiOperation("设置充电桩为故障中")
    public String setChargingPileCracked(@PathVariable int id) {
        log.info("setChargingPileCracked");
        chargingPileService.setChargingPileCracked(id);
        return "设置成功";
    }

    //删除充电桩
    @DeleteMapping("/deleteChargingPile")
    @ApiOperation("删除充电桩")
    public String deleteChargingPile(Integer id) {
        log.info("删除充电桩");
        chargingPileService.deleteChargingPile(id);
        return "删除成功";
    }

    //批量删除
    @PostMapping("/batchDelete")
    @ApiOperation("批量删除充电桩信息")
    public String deleteChargingPileBatch(@RequestBody int[] ids) {
        log.info("deleteChargingPileBatch");
        for (int id : ids) {
            chargingPileService.deleteChargingPile(id);
        }
        return "删除成功";
    }

    //新增充电桩
    @PostMapping("/addChargingPile")
    @ApiOperation("新增充电桩")
    public String addChargingPile(ChargingPile chargingPile) {
        log.info("新增充电桩");
        chargingPileService.addChargingPile(chargingPile);
        return "新增成功";
    }

    //修改充电桩
    @PutMapping("/updateChargingPile")
    @ApiOperation("修改充电桩")
    public String updateChargingPile(@RequestBody ChargingPile chargingPile) {
        log.info("修改充电桩");
        log.info("updateChargingPile: {}", chargingPile);
        chargingPileService.updateChargingPile(chargingPile);
        return "修改成功！";
    }

    @PostMapping("/createChargingPilesWithChargingGun")
    @ApiOperation("新增充电桩和充电枪")
    public List<ChargingGun> createChargingPilesWithChargingGun(
            @RequestBody PileAndGunRequest request) {
        return chargingPileService.createChargingPileWithChargingGuns(
                request.getChargingPile(), request.getChargingGuns());
    }

    @PostMapping("/updateChargingPilesWithChargingGun")
    @ApiOperation("修改充电桩和充电枪")
    public ResponseEntity<?> updateChargingPilesWithChargingGun(
            @RequestBody PileAndGunRequest request) {
        if (request == null) {
            log.error("Request body is null");
            throw new IllegalArgumentException("请求体不能为空");
        }
        if (request.getChargingPile() == null) {
            log.error("ChargingPiles参数为空");
            throw new IllegalArgumentException("充电桩参数不能为空");
        }
        log.info("Received ChargingPiles: " + request.getChargingPile());
        log.info("Received ChargingGuns: " + request.getChargingGuns());
        return ResponseEntity.ok(
                chargingPileService.updateChargingPilesWithChargingGun(
                        request.getChargingPile(), request.getChargingGuns()));
    }

    //根据充电桩id查找充电桩并加上充电站位置信息
    @GetMapping("/getChargingPileById/{id}")
    @ApiOperation("根据充电桩id查找充电桩并加上充电站位置信息")
    public Map<String, Object> getChargingPileById(@PathVariable Integer id) {
        log.info("根据充电桩id查找充电桩并加上充电站位置信息");

        // 查询充电桩信息
        ChargingPile chargingPile = chargingPileService.getChargingPileById(id);
        if (chargingPile == null) {
            throw new RuntimeException("Charging pile not found with id: " + id);
        }

        // 查询充电站信息
        Station station = stationService.getById(chargingPile.getStationId());
        if (station == null) {
            throw new RuntimeException("Station not found with id: " + chargingPile.getStationId());
        }

        // 构造返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("id", chargingPile.getId());
        result.put("pileName", chargingPile.getPileName());
        result.put("pileCode", chargingPile.getPileCode());
        result.put("pileType", chargingPile.getPileType());
        result.put("pilePower", chargingPile.getPilePower());
        result.put("pileModel", chargingPile.getPileModel());
        result.put("pileDesc", chargingPile.getPileDesc());
        result.put("pileStatus", chargingPile.getPileStatus());
        result.put("stationId", chargingPile.getStationId());
        result.put("suitableVehicle", chargingPile.getSuitableVehicle());
        result.put("pileImgUrl", chargingPile.getPileImgUrl());
        result.put("address", station.getAddress()); // 添加地址信息

        return result;
    }


}
